package embed_folder

import (
	"embed"
	"io/fs"
	"log"
	"net/http"
	"strings"

	"github.com/gin-contrib/static"
)

//
// static 库的 embedFileSystem 逻辑有问题，
// 在官方修复前用自己的 embedFileSystem。
//

type embedFileSystem struct {
	http.FileSystem
}

func (e embedFileSystem) Exists(prefix string, path string) bool {
	if prefix != "" {
		path = strings.TrimPrefix(path, prefix)
	}

	_, err := e.Open(path)
	return err == nil
}

func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
	fsys, err := fs.Sub(fsEmbed, targetPath)
	if err != nil {
		log.Fatalf("embed_folder.EmbedFolder - Invalid targetPath value - %s", err)
	}
	return embedFileSystem{
		FileSystem: http.FS(fsys),
	}
}
